//
//  CompressFilesManager.m
//  Runner
//
//  Created by 显铭 on 2020/4/21.
//  Copyright © 2020 The Chromium Authors. All rights reserved.
//

#import "CompressManager.h"
#import "VideoCompressTool.h"

#define LOCALDIR [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
#define VIDEOS_PATH(string) [LOCALDIR stringByAppendingPathComponent:string]

@interface CompressManager ()
/// 压缩文件夹
@property (nonatomic, copy) NSString *dirPath;
@property (nonatomic, strong) VideoCompressTool *compressTool;
@end

static CompressManager *_singleInstance = nil;

@implementation CompressManager

+ (instancetype)shareInstance
{
    if (_singleInstance == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (_singleInstance == nil) {
                _singleInstance = [[self alloc]init];
                [_singleInstance createDirectory];
            }
        });
    }
    
    return _singleInstance;
}

#pragma mark --- 创建文件夹
- (void)createDirectory {
    //创建文件夹
    self.dirPath = VIDEOS_PATH(@"compressedVideos");
    if (![[NSFileManager defaultManager] fileExistsAtPath:self.dirPath]) {
        if ([[NSFileManager defaultManager] createDirectoryAtPath:self.dirPath withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@"创建文件夹成功，目录 = %@", self.dirPath);
        }
    }
}

//压缩视频
- (void)compressVideo:(AVURLAsset *)videoAsset whenSuccess:(void(^)(NSString *compressedPath))successHandler  progressHandler:(void(^)(float progress))progressHandler failure:(void(^)(NSError *error))failure {
    //创建文件
    NSString *outputPath = [self.dirPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", [self currentDateAndTime]]];
    NSLog(@"video outputPath = %@",outputPath);
    
    _compressTool = [VideoCompressTool new];
    
    [_compressTool compressVideoWithAsset:videoAsset withBiteRate:nil withFrameRate:nil withVideoWidth:nil withVideoHeight:nil outputPath:outputPath compressComplete:^(id  _Nonnull responseObjc) {
        
        if ([responseObjc isKindOfClass:[NSError class]]) {//压缩失败
            dispatch_async(dispatch_get_main_queue(), ^{
                failure((NSError *)responseObjc);
            });
        } else {//压缩完成
            dispatch_async(dispatch_get_main_queue(), ^{
                successHandler((NSString *)responseObjc);
            });
        }
    } progressHandler:progressHandler];
}

///取消压缩
- (void)cancelCompressing {
    [_compressTool cancelCompressing];
}


#pragma mark --- 获取当前时间戳
- (NSString *)currentDateAndTime {
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYYMMddHHmmssSSS"];
    [dateFormatter setTimeZone:zone];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}


#pragma mark --- 获取缩略图
- (void)getVideoImageFromPHAsset:(PHAsset *)asset
                        forSize:(CGSize)size
                        completedResultBack:(void (^)(UIImage *image))resultCallback
{
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    option.resizeMode = PHImageRequestOptionsResizeModeFast;
    option.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    option.networkAccessAllowed = YES;
    
    CGSize imageSize;
    imageSize = size;
    
    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        UIImage *iamge = result;
        
        resultCallback(iamge);
        
    }];
    
}

@end
